const { querySql, queryOne } = require('../utils/index');
const { body, validationResult, query } = require('express-validator');
const boom = require('boom');
const jwt = require('jsonwebtoken');
const md5 = require('../utils/md5');
const passport = require('passport')
var fs = require('fs');
var COS = require('cos-nodejs-sdk-v5');
const {
  CODE_ERROR,
  CODE_SUCCESS,
  PRIVATE_KEY,
  JWT_EXPIRED,
  APPID,
  SECRETID,
  SECRETKRY
} = require('../utils/constant');
const SqlString = require('mysql/lib/protocol/SqlString');
const { resolve } = require('path');

var cos = new COS({
  AppId: APPID,
  SecretId: SECRETID,
  SecretKey: SECRETKRY,
});

var tengxun_cos = {
  Bucket: '1271981054',
  Region: 'ap-nanjing',
}

//查询userid信息
function getUserInfo(req, res, next) {
  // let { userid } = req.body;
  findUser().then(data => {
    // console.log('用户注册===', data);
    if (data) {
      res.json({
        code: CODE_SUCCESS,
        msg: '用户已存在',
        data: data
      })
    } else {
      res.json({
        code: CODE_ERROR,
        msg: '查询不到该用户',
        data: false
      })
    }
  })
}
function getAllShopCate(req, res, next) {
  const query = `select * from shopCate`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}

function getShopList(req, res, next) {
  let { id } = req.body;
  if (id == null) {
    var query = `select * from shop`
  } else {
    id = parseInt(id)
    var query = `select * from shop where shop_cate_id=${id}`
  }

  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getShopOne(req, res, next) {
  let { id } = req.body;
  id = parseInt(id)
  const query = `select * from shop where shop_id=${id}`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })

}
function getSwipterList(req, res, next) {
  const query = `select * from swipter`
  querySql(query).then(data => {
    console.log(data)
    var array = data
    var arrayString = ''
    for (var i = 1; i <= array.length; i++) {
      arrayString = arrayString + i + ','
    }
    arrayString = arrayString.substr(0, arrayString.length - 1);
    console.log(arrayString)
    const query1 = `select * from shop where shop_id in(${arrayString})`
    console.log(query1)
    querySql(query1).then(data1 => {
      if (!data1) {
        res.json({
          code: CODE_ERROR,
          msg: '查询失败',
          data: null
        })
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: '查询成功',
          data: data1
        })
      }
    })
  })
}
// 通过用户名查询用户信息
function findUser() {
  const query = `select * from admin`;
  return queryOne(query);
}
//添加地址
function addAddressInfo(req, res, next) {
  let { userid, name, phone, province, city, county, fulladdress, defaultaddress } = req.body;
  const query = `insert into address(user_id, name ,phone, province, city, county, fulladdress, defaultaddress) values('${userid}', '${name}' , '${phone}' , '${province}' , '${city}' , '${county}', '${fulladdress}', '${defaultaddress}')`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '添加失败',
        data: null
      })
    } else {
      const query1 = `select * from address where user_id = '${userid}' order by address_id desc`
      querySql(query1).then(data1 => {
        res.json({
          code: CODE_SUCCESS,
          msg: '添加成功',
          data: data1
        })
      })

    }
  })
}

function getMyAddressList(req, res, next) {
  let { user_id } = req.body
  const query = `select * from address where user_id='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
//添加计划
function addPlan(req, res, next) {
  let { user_id, nickname, avatar, plan, shop_id, address_id } = req.body;
  const query = `insert into form(user_id,plan,shop_id,address_id,nickname,avatar) values ('${user_id}','${plan}','${shop_id}','${address_id}','${nickname}','${avatar}')`
  console.log(query)
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '添加失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '添加成功',
        data: data
      })
      const query1 = 'update shop set apply_sum = apply_sum + 1'
      queryOne(query1)
    }
  })
}
function getAllPlanUser(req, res, next) {
  var idList = []
  let { shop_id } = req.body;
  const query = `select (nickname,avatar) from form where shop_id=${shop_id}`
  querySql(query).then(data => {
    console.log(data)
    for (var i = 0; i < data.length; i++) {
      idList.push(data[i].user_id)
    }

    console.log(idList)
    res.json({
      code: CODE_ERROR,
      msg: 'success',
      data: null
    })
  })
}
function getAllApplyInfo(req, res, next) {
  let { id } = req.body
  const query = `select * from form where shop_id=${id}`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function isApplyed(req, res, next) {
  let { id, shop_id } = req.body
  const query = `select * from form where shop_id=${shop_id} and user_id='${id}'`
  querySql(query).then(data => {
    if (data.length == 0) {
      res.json({
        code: CODE_ERROR,
        msg: '该用户未参与',
        data: false
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '该用户已参与',
        data: true
      })
    }
  })
}
function getAllarticleCate(req, res, next) {
  const query = `select * from articleCate`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getArticleList(req, res, next) {
  let { cate } = req.body
  if (cate == null) {
    var query = `select user_id,nickname,avatar,title,article_id,content,create_time,type,picture,cate,isrecommend,update_time,publish_status from article `
  } else {
    var query = `select user_id,nickname,avatar,title,article_id,content,create_time,type,picture,cate,isrecommend,update_time,publish_status from article where cate=${cate}`
  }

  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getMyArticleList(req, res, next) {
  let { user_id } = req.body
  const query = `select user_id,nickname,avatar,title,article_id,content,create_time,type,picture,isrecommend from article where user_id='${user_id}'`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getHotArticleList(req, res, next) {
  const query = `select user_id,nickname,avatar,title,article_id,create_time,type,picture,isrecommend from article where isrecommend=1`
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getArticleDetail(req, res, next) {
  let { id } = req.body
  const query = 'select * from article where article_id=' + id
  queryOne(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function searchArticle(req, res, next) {
  let { content } = req.body
  const query = `select user_id,nickname,avatar,title,article_id,create_time,type,picture,isrecommend from article where title like '%${content}%'`
  querySql(query).then(data => {
    if (!data) {
      const query1 = `select user_id,nickname,avatar,title,article_id,create_time,type,picture,isrecommend from article content title like '%${content}%'`
      querySql(query1).then(data1 => {
        if (!data1) {
          res.json({
            code: CODE_ERROR,
            msg: '查询失败',
            data: null
          })
        } else {
          res.json({
            code: CODE_SUCCESS,
            msg: '查询成功',
            data: data1
          })
        }
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function addComment(req, res, next) {
  let { user_id, user_name, avatar, article_id, article_title, comment_level, content, status, create_time } = req.body
  const query = `insert into comment(user_id,user_name,avatar,article_id,article_title,comment_level,content,status,create_time) values ('${user_id}','${user_name}','${avatar}','${article_id}','${article_title}',${comment_level},'${content}',${status},'${create_time}') `
  console.log(query)
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '插入失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '插入成功',
        data: data
      })
    }
  })
}
function addReplyComment(req, res, next) {
  let { user_id, user_name, avatar, article_id, article_title, parent_comment_id, parent_comment_user_id, reply_comment_id, reply_comment_user_id, comment_level, content, status, create_time } = req.body
  const query = `insert into comment(user_id,user_name,avatar,article_id,article_title,parent_comment_id,parent_comment_user_id,reply_comment_id,reply_comment_user_id,comment_level,content,status,create_time) values ('${user_id}','${user_name}','${avatar}','${article_id}','${article_title}','${parent_comment_id}','${parent_comment_user_id}','${reply_comment_id}','${reply_comment_user_id}',${comment_level},'${content}',${status},'${create_time}') `
  console.log(query)
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '插入失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '插入成功',
        data: data
      })
    }
  })
}
function addArticle(req, res, next) {
  let { user_id, nickname, avatar, title, picture, content, cate, create_time, update_time, type, isdelete, isrecommend, hits, comment_sum, publish_status } = req.body
  const query = `insert into article(user_id, nickname, avatar, title, picture, content, cate, create_time, update_time, type, isdelete, isrecommend, hits, comment_sum, publish_status) values ('${user_id}','${nickname}','${avatar}','${title}','${picture}','${content}',${cate},'${create_time}','${update_time}',${type},${isdelete},${isrecommend},${hits},${comment_sum},${publish_status}) `
  console.log(query)
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '插入失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '插入成功',
        data: data
      })
    }
  })
}
function getComment(req, res, next) {
  let { id, comment_id } = req.body
  if (id.length != 0) {
    var query = `select * from comment where article_id=${id}`
  } else if (comment_id.length != 0) {
    var query = `select * from comment where id=${comment_id}`
  }
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function uploadFile(req, res, next) {
  // 文件路径
  var filePath = './' + req.file.path;
  // 文件类型
  var temp = req.file.originalname.split('.');
  var fileType = temp[temp.length - 1];
  var lastName = '.' + fileType;
  // 构建图片名
  var fileName = Date.now() + lastName;
  // 图片重命名
  fs.rename(filePath, fileName, (err) => {
    if (err) {
      res.end(JSON.stringify({ status: '102', msg: '文件写入失败' }));
    } else {
      var localFile = './' + fileName;
      var key = fileName;

      // 腾讯云 文件上传
      var params = {
        Bucket: tengxun_cos.Bucket,                         /* 必须 */
        Region: tengxun_cos.Region,                         /* 必须 */
        Key: key,                                           /* 必须 */
        FilePath: localFile,                                /* 必须 */
      }
      cos.sliceUploadFile(params, function (err, data) {
        if (err) {
          fs.unlinkSync(localFile);
          res.end(JSON.stringify({ status: '101', msg: '上传失败', error: JSON.stringify(err) }));
        } else {
          fs.unlinkSync(localFile);
          var imageSrc = 'https://1271981054-1256167451.cos.ap-nanjing.myqcloud.com/' + data.Key;
          console.log(imageSrc)
          res.end(JSON.stringify({ status: '100', msg: '上传成功', imageUrl: imageSrc }));
        }
      });
    }
  })
}
function addFollow(req, res, next) {
  let { focus_user_id, focus_user_name, focus_user_avatar, user_id, user_name, user_avatar, create_time } = req.body
  const query = `insert into follow(focus_user_id,focus_user_name,focus_user_avatar,user_id,user_name,user_avatar,create_time) values ('${focus_user_id}','${focus_user_name}','${focus_user_avatar}','${user_id}','${user_name}','${user_avatar}','${create_time}') `
  console.log(query)
  querySql(query).then(data => {
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '插入失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '插入成功',
        data: data
      })
    }
  })
}
function getFollowStatus(req, res, next) {
  let { focus_user_id, user_id } = req.body
  const query = `select * from follow where focus_user_id='${focus_user_id}' and user_id='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (data.length == 0) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getMyFollow(req, res, next) {
  let { user_id } = req.body
  const query = `select * from follow where user_id='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getMyFocus(req, res, next) {
  let { focus_user_id } = req.body
  const query = `select * from follow where focus_user_id='${focus_user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function searchAdmin(req, res, next) {
  let { nickname, type } = req.body
  if (type == 'follow') {
    //搜索我得粉丝
    var query = `select * from follow where  focus_user_name like '%${nickname}%'`
  } else if (type == 'focus') {
    var query = `select * from follow where user_name like '%${nickname}%'`
  }
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function cancelFollow(req, res, next) {
  let { focus_user_id, user_id } = req.body
  const query = `delete from follow where focus_user_id='${focus_user_id}' and user_id='${user_id}'`
  console.log(query)
  querySql(query).then(data => {

    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '删除失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '删除成功',
        data: data
      })
    }
  })
}
function getShopInfo(data) {
  return new Promise((resolve) => {
    // data.forEach(tem => {
    //   var shop_id = tem.shop_id
    //   const query1 = `select shop_name, picture from shop where shop_id=${shop_id}`
    //   console.log(query1)
    //   queryOne(query1).then(data1 => {
    //     tem.shopInfo = data1

    //   })
    // })
    // resolve(data)
    for (var i = 0; i < data.length; i++) {
      var shop_id = parseInt(data[i].shop_id)
      const query1 = `select shop_name, picture from shop where shop_id=${shop_id}`
      console.log(query1)
      queryOne(query1).then(data1 => {
        console.log(data)
        data[i].shopInfo = {}
        data[i]['shopInfo'] = data1

      })
    }
    resolve(data)
  })
}
function getMyShop(req, res, next) {
  let { user_id } = req.body
  const query = `select * from shop a,form b where a.shop_id=b.shop_id and b.user_id='${user_id}'`
  querySql(query).then(data => {
    console.log(query)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }

  })
}
function addCollection(req, res, next) {
  let { user_id, shop_id } = req.body
  const query = `insert into collection (shop_id,user_id) values(${shop_id},'${user_id}')`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '增加失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '增加成功',
        data: data
      })
    }
  })
}
function getMyCollection(req, res, next) {
  let { user_id } = req.body
  const query = `select * from collection a,shop b where a.shop_id = b.shop_id and a.user_id ='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getCollectionStatus(req, res, next) {
  let { shop_id, user_id } = req.body
  const query = `select * from collection where user_id='${user_id}' and shop_id=${shop_id} `
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function deleteMyCollection(req, res, next) {
  let { shop_id, user_id } = req.body
  const query = `delete from collection where shop_id=${shop_id} and user_id='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '删除失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '删除成功',
        data: data
      })
    }
  })
}
function getMyShopInfoList(req, res, next) {
  let { shop_id, user_id } = req.body
  const query = `select * from form a,shop b where a.shop_id = b.shop_id and a.user_id ='${user_id}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getAddressDetail(req, res, next) {
  let { id } = req.body
  const query = `select * from address where address_id=${id}`
  console.log(query)
  queryOne(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function updateAddress(req, res, next) {
  let { defaultaddress, fulladdress, county, city, province, phone, name, address_id, user_id } = req.body
  const query = `update address set name='${name}', phone='${phone}',province='${province}',city='${city}',county='${county}',fulladdress='${fulladdress}',defaultaddress='${defaultaddress}' where address_id=${address_id}`
  console.log(query)
  querySql(query).then(data => {
    // console.log(data)
    if (!data) {

      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      const query1 = `update address set defaultaddress=replace(defaultaddress,'1','0') where user_id='${user_id}'`
      console.log(query1)
      querySql(query1).then(data1 => {
        console.log(data1)
        const query2 = `update address set defaultaddress='${defaultaddress}' where address_id=${address_id}`
        querySql(query2)
      })
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function updateAdmin(req, res, next) {
  let { userid, sign, avatar, nickname } = req.body
  const query = `update admin set nickname='${nickname}',avatar='${avatar}',sign='${sign}' where userid='${userid}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function addQuestion(req, res, next) {
  let { create_time, content, user_id } = req.body
  const query = `insert into question (user_id,content,create_time) values ('${user_id}','${content}','${create_time}')`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '增加失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '增加成功',
        data: data
      })
    }
  })
}
function addShop(req, res, next) {
  let { introduction, limit_time, create_time, shop_cate_name, shop_cate_id, picture, content, price, sum, shop_name, status } = req.body
  const query = `insert into shop (shop_name,sum,price,content,shop_cate_id,shop_cate_name,picture,create_time,limit_time,introduction,status) values ('${shop_name}',${sum},${price},'${content}','${shop_cate_id}','${shop_cate_name}','${picture}','${create_time}','${limit_time}','${introduction}',${status})`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '增加失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '增加成功',
        data: data
      })
    }
  })
}

function updateShop(req, res, next) {
  let { shop_id, limit_time, create_time, shop_cate_name, shop_cate_id, content, picture, price, sum, shop_name } = req.body
  const query = `update shop set shop_name='${shop_name}',sum=${sum},price=${price},picture='${picture}',content='${content}',shop_cate_id='${shop_cate_id}',shop_cate_name='${shop_cate_name}',create_time='${create_time}',limit_time='${limit_time}' where shop_id=${shop_id} `
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '更新失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '更新成功',
        data: data
      })
    }
  })
}
function getAllAdmin(req, res, next) {
  let { } = req.body
  const query = `select * from admin`

  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function deleteShop(req, res, next) {
  let { shop_id } = req.body
  const query = `delete from shop where shop_id=${shop_id}`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '删除失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '删除成功',
        data: data
      })
    }
  })
}
function updateAdminForAdmin(req, res, next) {
  let { userid, address, nickname, avatar, phone } = req.body
  const query = `update admin set nickname='${nickname}' , address='${address}', avatar='${avatar}',phone='${phone}' where userid='${userid}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function deleteAdmin(req, res, next) {
  let { userid } = req.body
  const query = `delete from admin where userid='${userid}'`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '删除失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '删除成功',
        data: data
      })
    }
  })
}
function changeArticleStatus(req, res, next) {
  let { id } = req.body
  const query1 = `select publish_status from article where article_id=${id}`
  queryOne(query1).then(data1 => {
    if (!data1) {
      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      var a
      if (data1.publish_status == 1) {
        a = 0
      } else {
        a = 1
      }
      const query = `update article set publish_status=${a} where article_id=${id}`
      console.log(query)
      querySql(query).then(data => {
        console.log(data)
        if (!data) {
          res.json({
            code: CODE_ERROR,
            msg: '修改失败',
            data: null
          })
        } else {
          res.json({
            code: CODE_SUCCESS,
            msg: '修改成功',
            data: data
          })
        }
      })
    }
  })

}
function updateArticle(req, res, next) {
  let { id, update_time, cate, content, title, picture } = req.body
  const query = `update article set title='${title}' , content='${content}' , cate=${cate} , update_time='${update_time}' , picture='${picture}' where article_id=${id}`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function deleteArticle(req, res, next) {
  let { id } = req.body
  const query = `delete from article where article_id=${id}`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '删除失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '删除成功',
        data: data
      })
    }
  })
}
function getForm(req, res, next) {
  let { shop_id } = req.body
  const query = `select * from form where shop_id=${shop_id}`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function getUserList(req, res, next) {
  let { userList } = req.body
  console.log(userList)
  if (userList.length == 0) {
    res.json({
      code: CODE_SUCCESS,
      msg: '人数已满',
      data: null
    })
  } else {
    var chooseNum = ramdom(0, userList.length - 1)
    console.log("选中名单", chooseNum)
    res.json({
      code: CODE_SUCCESS,
      msg: '选取成功',
      data: chooseNum
    })
  }
}

function ramdom(minNum, maxNum) {
  return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
}

function determineChoose(req, res, next) {
  let { shop_id, chooseList, formList } = req.body
  chooseList.forEach(item => {
    var query = `update form set isChoosed = 1 where user_id='${item.user_id}' and shop_id=${shop_id}`
    console.log(query)
    queryOne(query)
    formList = formList.filter(i => i.user_id != item.user_id)
  })
  formList.forEach(item => {
    var query1 = `update form set isChoosed = 0 where user_id='${item.user_id}' and shop_id=${shop_id}`
    queryOne(query1)
  })
  var query2 = `update shop set status = 2 where shop_id=${shop_id}`
  queryOne(query)
  res.json({
    code: CODE_SUCCESS,
    msg: '选择成功',
    data: "success"
  })
}

function getFormAddressList(req, res, next) {
  let { shop_id } = req.body
  const query = `select * from form a,address b where a.address_id = b.address_id and a.shop_id =${shop_id} and isChoosed=1`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function updateAddressForm(req, res, next) {
  let { formAddressList } = req.body
  console.log(formAddressList)
  formAddressList.forEach(async item => {
    // return new Promise((resolve) => {
    const query = `update form set express='${item.expressNumber}' ,company='${item.expressCompany}' where user_id='${item.user_id}' and shop_id=${item.shop_id}`
    console.log(query);
    await queryOne(query)
  })
  var query1 = `update shop set status=3 where shop_id=${formAddressList[0].shop_id} `
  queryOne(query1)
  res.json({
    code: CODE_SUCCESS,
    msg: '修改成功',
    data: "success"
  })
}

function getReportList(req, res, next) {
  let { shop_id } = req.body
  const query = `select * from form a,article b where a.shop_id=${shop_id} and a.article_id=b.article_id`
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '查询失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '查询成功',
        data: data
      })
    }
  })
}
function passReport(req, res, next) {
  let { article_id, status } = req.body
  const query = `update article set publish_status=${status} where article_id=${article_id}`
  console.log(query)
  queryOne(query).then(data => {
    console.log(data)
    if (data) {
      res.json({
        code: CODE_ERROR,
        msg: '更新失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '更新成功',
        data: data
      })
    }
  })
}
function finishForm(req, res, next) {
  let { shop_id } = req.body
  const query = `update form set status = 5 where shop_id=${shop_id} and isChoosed=1`
  const query1 = `update shop set status = 4 where shop_id=${shop_id}`
  querySql(query1)
  console.log(query)
  querySql(query).then(data => {
    console.log(data)
    if (!data) {
      res.json({
        code: CODE_ERROR,
        msg: '修改失败',
        data: null
      })
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: '修改成功',
        data: data
      })
    }
  })
}
function changeIndex(req, res, next) {
  let { idList } = req.body
  const query = `delete from swipter`
  querySql(query)
  idList.forEach(item =>{
    var query1 = `insert into swipter (shop_id) values (${item})`
    console.log(query1)
    queryOne(query1)
  })
  res.json({
    code: CODE_SUCCESS,
    msg: '更新成功',
    data: "success"
  })
  
}

module.exports = {
  getUserInfo,
  getAllShopCate,
  getShopList,
  getSwipterList,
  getShopOne,
  addAddressInfo,
  getMyAddressList,
  addPlan,
  getAllPlanUser,
  getAllApplyInfo,
  isApplyed,
  getAllarticleCate,
  getArticleList,
  getHotArticleList,
  getMyArticleList,
  getArticleDetail,
  searchArticle,
  addComment,
  addReplyComment,
  getComment,
  uploadFile,
  addArticle,
  addFollow,
  getFollowStatus,
  getMyFollow,
  getMyFocus,
  searchAdmin,
  cancelFollow,
  getMyShop,
  addCollection,
  getMyCollection,
  getCollectionStatus,
  deleteMyCollection,
  getMyShopInfoList,
  getAddressDetail,
  updateAddress,
  updateAdmin,
  addQuestion,
  addShop,
  updateShop,
  deleteShop,
  getAllAdmin,
  updateAdminForAdmin,
  deleteAdmin,
  changeArticleStatus,
  updateArticle,
  deleteArticle,
  getForm,
  getUserList,
  determineChoose,
  getFormAddressList,
  updateAddressForm,
  getReportList,
  passReport,
  finishForm,
  changeIndex
}
